// 瀹㈡埛绔厤缃俊鎭被
package com.config;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.databus.*;

public class ClientCfg {
	private static final String cfgFileName = "clientcfg.xml";  // 瀹㈡埛绔厤缃枃浠跺悕绉�
	
	public class ServerAddr {
		public String mAddr;
		public int mPort;
	}
	
	public String mAppName="";                   // 绋嬪簭鍚嶇О
	public int mAppType = 1;                  // 绋嬪簭绫诲瀷
	public int mAppGroup = 1;                 // 绋嬪簭缁勫埆
	public String mUuid= UUID.randomUUID().toString();                      // UUID
	public String mAuth = "test";             // 楠岃瘉鐮�
	public ArrayList<Integer> mServiceList    = new ArrayList<Integer>();      // 鎻愪緵鐨勬湇鍔″垪琛�
	public ArrayList<String> mSubscribeList  = new ArrayList<String>();        // 璁㈤槄鍒楄〃
	public ArrayList<ServerAddr> mSrvAddrList = new ArrayList<ServerAddr>();   // 鏈嶅姟鍣ㄥ湴鍧�鍒楄〃
	public int mThreadNum = 2;                // 寮�鍚簨浠跺鐞嗙嚎绋嬫暟
	public int mBufferSize = 1000000;         // 缂撳啿鍖哄ぇ灏�
	public int mSendQueueSize = 10000;        // 鍙戦�侀槦鍒楀ぇ灏�
	public int mReceiveQueueSize = 10000;     // 鎺ユ敹闃熷垪澶у皬
	public int mConnectTimeOut = 6000;        // 杩炴帴瓒呮椂鏃堕棿
	public int mMaxHeartBeatTick = 5;         // 蹇冭烦妫�娴嬪皾璇曟鏁�
	public int mHeartBeatInterval = 5000;     // 蹇冭烦鍛ㄦ湡
	public int mBrokenInterval = 3000;        // 鏂嚎閲嶈繛鍛ㄦ湡
	public boolean mHeartBeatSwitch = true;   // 鏄惁寮�鍚績璺�
	public boolean mZlibSwitch = true;        // 鏄惁寮�鍚帇缂�
	public int mZlibThreshold = 1024;         // 鏁版嵁鍘嬬缉闃堝��
	

	public void AddBrokerAddress(String ipaddr,int port)
	{
		ServerAddr addr=new ServerAddr();
		addr.mAddr=ipaddr;
		addr.mPort=port;
		mSrvAddrList.add(addr);
	}

	public boolean LoadConfig(String cfgPath)
	{
		if(!cfgPath.endsWith("/") && !cfgPath.endsWith("\\"))
		{
			cfgPath += "/";
		}
		Log.info("Load Config file, cfgPath = " + cfgPath);

		File file = new File(cfgPath + cfgFileName);
		if(!file.exists() || !file.canRead())
		{
			Log.error("clientcfg.xml file is not exsist, cfgPath = " + cfgPath);
			return false;
		}
		
		SAXReader saxReader = new SAXReader();

		Document document = null;
		try {
			document = saxReader.read(file);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.error("read clientcfg file failed, cfgPath = " + cfgPath);
			return false;
		}
		return load(document);
	}
	public boolean LoadUrl(String url)
	{
		SAXReader saxReader = new SAXReader();

		Document document = null;
		try {
			document = saxReader.read(url);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.error("read clientcfg file failed,url = " + url);
			return false;
		}
		return load(document);
	}
	public boolean LoadStream(InputStream in)
	{
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			document = saxReader.read(in);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.error("read clientcfg file from inputstream failed " );
			return false;
		}
		return load(document);
	}
	private boolean load(Document document)
	{
		Element root = document.getRootElement();
		Element client = root.element("client");
		if(null == client)
		{
			Log.error("can not get client info node!");
			return false;
		}
		Element appName = client.element("appName");
		if(null != appName)
		{
			mAppName = appName.getText();
		}
		Element appType = client.element("appType");
		if(null != appType)
		{
			mAppType = Integer.parseInt(appType.getText());
		}
		Element appGroup = client.element("appGroup");
		if(null != appGroup)
		{
			mAppGroup = Integer.parseInt(appGroup.getText());
		}
		Element uuid = client.element("uuid");
		if(null != uuid)
		{
			mUuid = uuid.getText();
		}
		Element auth = client.element("auth");
		if(null != auth)
		{
			mAuth = auth.getText();
		}
		Element serviceList = client.element("serviceList");
		if(null != serviceList)
		{
			for (Iterator<?> iter = serviceList.elementIterator(); iter.hasNext();)
			{
				Element service = (Element) iter.next();
				mServiceList.add(Integer.parseInt(service.getText()));
			}
		}
		Element subscribeList = client.element("subscribeList");
		if(null != subscribeList)
		{
			for (Iterator<?> iter = subscribeList.elementIterator(); iter.hasNext();)
			{
				Element topic = (Element) iter.next();
				mSubscribeList.add(topic.getText());
			}
		}

		Element serverGroup = root.element("serverGroup");
		if(null == serverGroup)
		{
			Log.error("can not get serverGroup info node!");
			return false;
		}
		else
		{
			for (Iterator<?> iter = serverGroup.elementIterator(); iter.hasNext();)
			{
				Element server = (Element) iter.next();
				if(server.getName().equals("server"))
				{
					ServerAddr addr = new ServerAddr();
					addr.mAddr = server.attributeValue("IP");
					addr.mPort = Integer.parseInt(server.attributeValue("port"));
					mSrvAddrList.add(addr);
				}
			}
		}

		Element heartbeat = root.element("heartbeat");
		if(null != heartbeat)
		{
			Element maxHeartBeatTick = heartbeat.element("maxHeartBeatTick");
			if(null != maxHeartBeatTick)
			{
				mMaxHeartBeatTick = Integer.parseInt(maxHeartBeatTick.getText());
			}
			Element hearbeatinterval = heartbeat.element("hearbeatinterval");
			if(null != hearbeatinterval)
			{
				mHeartBeatInterval = Integer.parseInt(hearbeatinterval.getText());
			}
			Element brokeninterval = heartbeat.element("brokeninterval");
			if(null != brokeninterval)
			{
				mBrokenInterval = Integer.parseInt(brokeninterval.getText());
			}
			Element heartbeatswitch = heartbeat.element("switch");
			if(null != heartbeatswitch)
			{
				mHeartBeatSwitch = heartbeatswitch.getText().equals("1");
			}
		}
		else
		{
			Log.warn("can not get heartbeat info node!");
		}


		Element zlib = root.element("zlib");
		if(null != zlib)
		{
			Element zlibswitch = zlib.element("switch");
			if(null != zlibswitch)
			{
				mZlibSwitch = zlibswitch.getText().equals("1");
			}
			Element threshold = zlib.element("threshold");
			if(null != threshold)
			{
				mZlibThreshold = Integer.parseInt(threshold.getText());
			}
		}
		else
		{
			Log.warn("can not get zlib info node!");
		}

		Element connection = root.element("connection");
		if(null != connection)
		{
			Element timeout = connection.element("timeout");
			if(null != timeout)
			{
				mConnectTimeOut = Integer.parseInt(timeout.getText());
			}
		}
		else
		{
			Log.warn("can not get connection info node!");
		}

		Element performance = root.element("performance");
		if(null != performance)
		{
			Element threadNum = performance.element("threadNum");
			if(null != threadNum)
			{
				mThreadNum = Integer.parseInt(threadNum.getText());
				mThreadNum = mThreadNum > 2 ? mThreadNum : 2;
			}
			Element buffersize = performance.element("buffersize");
			if(null != buffersize)
			{
				mBufferSize = Integer.parseInt(buffersize.getText());
			}
			Element recvqueuesize = performance.element("recvqueuesize");
			if(null != recvqueuesize)
			{
				mReceiveQueueSize = Integer.parseInt(recvqueuesize.getText());
			}
			Element sendqueuesize = performance.element("sendqueuesize");
			if(null != sendqueuesize)
			{
				mSendQueueSize = Integer.parseInt(sendqueuesize.getText());
			}
		}
		else
		{
			Log.warn("can not get performance info node!");
		}

		return true;
	}
}
